<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

/**
 * 系统菜单分组控制器
 * @package App\Http\Controllers\Admin
 */
class SysMenuGroupController extends BaseController
{
    private $menuSer;

    public function __construct()
    {
        parent::__construct();
        $this->menuSer = new \App\Services\System\Menu();
    }

    /**
     * 系统菜单分组管理
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $pageSize = $request->input('pageSize', 10);
        $query = \App\Models\System\MenuGroup::query()->select('*');
        $name = $request->get('name', '');
        if ($name) {
            $query->where('group_name', 'like', '%' . $name . '%');
        }
        $key = $request->get('key', '');
        if ($key) {
            $query->where('group_key', 'like', '%' . $key . '%');
        }
        $paginater = $query->paginate($pageSize, ['*'], 'pageNo');
        return $this->success(
            '加载成功',
            [
                'list' => $paginater->items(),
                'total' => $paginater->total(),
            ]
        );
    }

    /**
     * 新建分组
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(Request $request)
    {
        $exceptId = (int)$request->input('group_id', 0);
        $this->validate($request, [
            'group_key' => 'required|unique:sys_menu_groups,group_key,' . $exceptId . ',group_id',
            'group_name' => 'required',
        ]);
        if ($this->menuSer->saveGroup($request->toArray())) {
            return $this->success(($request->group_id ? '编辑' : '新增') . '成功');
        } else {
            return $this->error('error');
        }
    }

    /**
     * 删除
     * @param Request $request
     */
    public function destroy(Request $request)
    {
        if ($this->menuSer->delGroup($request->input('group_ids', []))) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
}
